<template>
  <div class="upload-image-container">
    <el-upload
      :http-request="customRequest"
      :show-file-list="false"
      :accept="fileType.join(',')"
      :disabled="disabled"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      multiple
    >
      <div class="image-preview-container">
        <div v-for="(image, index) in modelValue" :key="index" class="image-item">
          <template v-if="isImage(image)">
            <img :src="image" alt="预览图片" class="preview-media" />
          </template>

          <template v-else-if="isVideo(image)">
            <video :src="image" controls class="preview-media"></video>
          </template>
          <div v-if="!disabled" class="image-actions">
            <el-button size="small" @click.stop="openVideoPreview(image)">查看</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(index)">删除</el-button>
          </div>
        </div>
        <div v-if="modelValue.length < maxCount" class="upload-placeholder">
          <el-icon><Plus /></el-icon>
          <span>点击上传</span>
        </div>
      </div>
    </el-upload>
  </div>

  <!-- 视频放大预览模态框 -->
  <div v-if="videoPreviewVisible" class="video-preview-modal" @click="videoPreviewVisible = false">
    <div class="video-preview-content" @click.stop>
      <video :src="currentVideoUrl" controls class="preview-large"></video>
    </div>
  </div>

  <!-- 图片放大预览模态框 -->
  <div v-if="imagePreviewVisible" class="image-preview-modal" @click="imagePreviewVisible = false">
    <div class="image-preview-content" @click.stop>
      <img :src="currentImageUrl" class="preview-large" alt="图片预览" />
    </div>
  </div>
</template>


<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/config/axios'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  fileSize: {
    type: Number,
    default: 50
  },
  fileType: {
    type: Array,
    default: () => [
      // 图片类型
      'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp',
      // 视频类型
      'video/mp4', 'video/webm', 'video/ogg', 'video/mov'
    ]
  },
  maxCount: {
    type: Number,
    default: 9
  }
})

const emit = defineEmits(['update:modelValue'])

const videoPreviewVisible = ref(false)
const currentVideoUrl = ref('')
const imagePreviewVisible = ref(false)
const currentImageUrl = ref('')

const openVideoPreview = (url) => {
  if (isImage(url)) {
    currentImageUrl.value = url
    imagePreviewVisible.value = true
  } else {
    currentVideoUrl.value = url
    videoPreviewVisible.value = true
  }
}

const isImage = (url) => {
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
  const ext = url.split('.').pop()?.toLowerCase();
  return imageExtensions.includes(ext);
};

const isVideo = (url) => {
  const videoExtensions = ['mp4', 'webm', 'ogg', 'mov'];
  const ext = url.split('.').pop()?.toLowerCase();
  return videoExtensions.includes(ext);
};

const beforeUpload = (rawFile) => {
  // 检查文件大小
  const isLtSize = rawFile.size / 1024 / 1024 < props.fileSize
  if (!isLtSize) {
    ElMessage.warning(`上传图片大小不能超过 ${props.fileSize}MB!`)
    return false
  }
  
  // 检查文件类型
  const isTypeValid = props.fileType.includes(rawFile.type)
  if (!isTypeValid) {
    ElMessage.warning('上传图片格式不正确!')
    return false
  }
  
  // 检查数量限制
  if (props.modelValue.length >= props.maxCount) {
    ElMessage.warning(`最多只能上传 ${props.maxCount} 张图片!`)
    return false
  }
  
  return true
}

const customRequest = ({ file, onSuccess, onError }) => {
  const formData = new FormData()
  formData.append('file', file)
  
  request.post('/file/upload', formData)
    .then(res => {
      // 假设后端返回的图片地址在 res.data 中
      const imageUrl = res.data || res
      // 将新图片添加到数组
      const newImages = [...props.modelValue, imageUrl]
      emit('update:modelValue', newImages)
      onSuccess(res)
      ElMessage.success('上传成功')
    })
    .catch(err => {
      onError(err)
      ElMessage.error('上传失败')
    })
}

const handleDelete = (index) => {
  const newImages = props.modelValue.filter((_, i) => i !== index)
  emit('update:modelValue', newImages)
}
</script>

<style scoped>
.upload-image-container {
  display: inline-block;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  width: 150px;
  height: 150px;
  position: relative;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px;
  display: flex;
  justify-content: center;
}

.upload-placeholder {
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.upload-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
}


.video-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.video-preview-content {
  max-width: 90%;
  max-height: 90%;
}

.preview-large {
  width: 100%;
  height: 100%;
  object-fit: contain;
}


  .video-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  .video-preview-content {
    max-width: 90%;
    max-height: 90%;
  }

  .preview-large {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .image-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .image-preview-content {
    max-width: 90%;
    max-height: 90%;
  }

  .preview-large {
    max-width: 100%;
    max-height: 80vh;
    object-fit: contain;
  }
</style>